package com.bootx.predict;

import com.bootx.predict.pojo.PredictPlugin;
import com.bootx.predict.pojo.PredictionResult;
import com.bootx.predict.pojo.RedPacketBatch;
import com.bootx.predict.util.PredictUtils;
import com.bootx.util.JsonUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author black
 * 基础频率法
 */
@Component("basePredict")
public class BasePredict extends PredictPlugin {
    @Override
    public String getName() {
        return "basePredict";
    }

    @Override
    public List<PredictionResult> predict (List<RedPacketBatch> batches, Set<Integer> indexes){
        System.out.println("预测的数据："+JsonUtils.toJson(batches));
        Map<Integer, List<RedPacketBatch.RedPacketDetail>> grouped = new HashMap<>();
        for (RedPacketBatch batch : batches) {
            for (RedPacketBatch.RedPacketDetail packet : batch.getRedPackets()) {
                grouped.computeIfAbsent(packet.getIndex(), k -> new ArrayList<>()).add(packet);
            }
        }

        // 计算每个 index 的统计
        List<PredictionResult> results = new ArrayList<>();
        for (Map.Entry<Integer, List<RedPacketBatch.RedPacketDetail>> entry : grouped.entrySet()) {
            int index = entry.getKey();
            List<RedPacketBatch.RedPacketDetail> list = entry.getValue();
            int total = list.size();
            int oddCount = (int) list.stream().filter(p -> PredictUtils.isAmountOdd(p.getAmount())).count();
            double avgOpenTime = list.stream().mapToInt(RedPacketBatch.RedPacketDetail::getOpenTime).average().orElse(0);
            double oddProbability = total > 0 ? (double) oddCount / total : 0.5;
            results.add(new PredictionResult(index, total, oddCount, oddProbability, Double.valueOf(avgOpenTime+"").intValue()));
        }

        // 找出概率最高的一项
        PredictionResult best = results.stream()
                .max(Comparator.comparingDouble(PredictionResult::getOddProbability))
                .orElse(null);

        return results;
    }

    // 内部类用于统计
    static class Stat {
        int total = 0;
        int oddCount = 0;
        int openTimeSum = 0;
    }
}
